<template>
  <div class="app-container">
    <el-row style="width: 100%;height: 100%;margin: 0;" :gutter="10">
      <!--区域数据-->
      <el-col :span="4" style="height: 100%;padding-left: 0;">
        <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
          <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                    style="width: 100%;" v-model="filterText"/>
          <div style="max-height:96%;overflow-y: auto;margin-top: 10px;" class="treeCont">
            <el-tree
              :data="sheetsTreeList"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              :default-expanded-keys="defaultExpandedKeys"
              highlight-current
              v-loading="treeLoading"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data}">
                <div class="custom-tree-node"
                     style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                  <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                  <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                  <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>
                  <span>{{ node.label }}</span>
                  <span v-if="data.deviceCount!=null" class="device-count">({{data.deviceCount}})</span>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="20" style="height: 100%;background-color: #FFFFFF;padding: 10px;">
        <el-row class="line-bottom" v-show="showSearch">
          <el-col class="form_col">
            <el-form :model="queryParams" ref="queryForm" :size="formItemSize" v-show="showSearch"
                     label-width="80px">
              <div id="searchFilter" style="display: flex; flex-wrap: wrap">
                <el-form-item label="设备名称" prop="terminalName">
                  <el-input
                    v-model="queryParams.terminalName"
                    placeholder="请输入设备名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="设备编号" prop="terminalId">
                  <el-input
                    v-model="queryParams.terminalId"
                    placeholder="请输入设备编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="所属客户" prop="tenantId">
                  <el-select filterable v-model="queryParams.tenantId" placeholder="请选择所属客户" style="width: 100%;">
                    <el-option
                      v-for="dept in deptOption"
                      :key="dept.tenantId"
                      :label="dept.deptName"
                      :value="dept.tenantId"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="IMEI" prop="imei">
                  <el-input
                    v-model="queryParams.imei"
                    placeholder="请输入IMEI"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="注册平台" prop="signPlatform">
                  <el-select filterable v-model="queryParams.signPlatform" placeholder="请选择注册平台" style="width: 100%;">
                    <el-option v-for="dict in dict.type.sign_platform" :key="dict.value" :label="dict.label"
                               :value="parseInt(dict.value)"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="使用状态" prop="terminalMark">
                  <el-select filterable v-model="queryParams.terminalMark" placeholder="请选择使用状态" style="width: 100%;">
                    <el-option v-for="dict in dict.type.used_status" :key="dict.value" :label="dict.label"
                               :value="parseInt(dict.value)"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-form>
          </el-col>

          <el-col class="form_query">
            <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
            </el-button>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['basedata:terminalsdb:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['basedata:terminalsdb:remove']"
            >批量删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['basedata:terminalsdb:import']"
            >导入
            </el-button>
          </el-col>

          <RightDropdown :columns="columns" :showSearch.sync="showSearch" @queryTable="getList" @export="handleExport"
                         :hasPermiExport="['basedata:terminalsdb:export']"></RightDropdown>
        </el-row>

        <el-table v-loading="loading" :data="terminalsdbList" size="mini" row-key="id" border
                  :height="getAvailableHeight"
                  @selection-change="handleSelectionChange" default-expand-all
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}" :default-sort="defaultSort"
                  @sort-change="handleSorterChange">
          <el-table-column type="selection" width="55" align="center" fixed :selectable="selectable"/>
          <el-table-column label="设备编号" align="center" prop="terminalId" v-if="columns[1].visible"
                           :show-overflow-tooltip="true" width="150" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <router-link :to="{name: 'HistoryDb',params: {locationNb: scope.row.locationNb, tid: scope.row.id, terminalId: scope.row.terminalId}}"><span style="color: #00afff">{{scope.row.terminalId}}</span></router-link>
            </template>
          </el-table-column>
          <el-table-column label="设备名称" align="center" prop="terminalName" v-if="columns[0].visible"
                           :show-overflow-tooltip="true" width="150" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="表状态" align="center" prop="terminalMark" v-if="columns[2].visible"
                           :show-overflow-tooltip="true" width="90" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.used_status" :value="scope.row.terminalMark"/>
            </template>
          </el-table-column>
          <el-table-column label="表型号" align="center" prop="typeId" v-if="columns[3].visible"
                           :show-overflow-tooltip="true" width="180" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.module_type" :value="scope.row.typeId"/>
            </template>
          </el-table-column>
          <el-table-column label="表底数" align="center" prop="baseReading" v-if="columns[4].visible"
                           :show-overflow-tooltip="true" sortable="custom" width="90"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="厂家名称" align="center" prop="supplierId" v-if="columns[5].visible"
                           :show-overflow-tooltip="true" width="100" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.terminal_supplier" :value="scope.row.supplierId"/>
            </template>
          </el-table-column>
          <el-table-column label="安装日期" align="center" prop="installDate" v-if="columns[6].visible"
                           :show-overflow-tooltip="true" width="100" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
          </el-table-column>
          <el-table-column label="安装地址" align="center" prop="installAddress" v-if="columns[7].visible"
                           :show-overflow-tooltip="true" width="180" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="IMEI" align="center" prop="imei" v-if="columns[8].visible"
                           :show-overflow-tooltip="true"
                           width="150" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="SIM卡号" align="center" prop="simNum" v-if="columns[9].visible"
                           :show-overflow-tooltip="true" sortable="custom" width="100"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="钢印/塑封号" align="center" prop="plasticSealNo" v-if="columns[10].visible"
                           :show-overflow-tooltip="true" width="120" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="出厂编号" align="center" prop="firstSupplierId" v-if="columns[11].visible"
                           :show-overflow-tooltip="true" width="130" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="是否带阀控" align="center" prop="valveControl" v-if="columns[12].visible"
                           :show-overflow-tooltip="true" width="110" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.yes_no" :value="scope.row.valveControl"/>
            </template>
          </el-table-column>
          <!--        2024-12-19新增字段-->
          <el-table-column label="阀门状态" align="center" prop="valveStatus" v-if="columns[23].visible"
                           :show-overflow-tooltip="true" width="110" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
<!--              <dict-tag :options="dict.type.yes_no" :value="scope.row.valveControl"/>-->
              <el-tag type="success" v-if="scope.row.valveStatus === 0">开</el-tag>
              <el-tag type="info" v-if="scope.row.valveStatus === 1">关</el-tag>
              <el-tag type="danger" v-if="scope.row.valveStatus === 2">无状态</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="阀门地址" align="center" prop="valveAddress" v-if="columns[13].visible"
                           :show-overflow-tooltip="true" sortable="custom" width="100"
                           :sort-orders="['ascending', 'descending']"/>
<!--          <el-table-column label="阀门地址" align="center" prop="valveAddress" v-if="columns[13].visible"-->
<!--                           :show-overflow-tooltip="true" sortable="custom" width="100"-->
<!--                           :sort-orders="['ascending', 'descending']"/>-->
          <el-table-column label="出厂日期" align="center" prop="manufactureDate" v-if="columns[14].visible"
                           :show-overflow-tooltip="true" sortable="custom" width="100"
                           :sort-orders="['ascending', 'descending']">
          </el-table-column>
          <el-table-column label="口径大小" align="center" prop="caliber" v-if="columns[15].visible"
                           :show-overflow-tooltip="true" width="100" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.ldbd_pipe_caliber" :value="scope.row.caliber"/>
            </template>
          </el-table-column>
          <el-table-column label="采集频率(分钟)" align="center" prop="readingFrequency" v-if="columns[16].visible"
                           :show-overflow-tooltip="true" width="140" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="上传频率(分钟)" align="center" prop="upFrequency" v-if="columns[17].visible"
                           :show-overflow-tooltip="true" width="140" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="位置识别编号" align="center" prop="locationNb" v-if="columns[18].visible"
                           :show-overflow-tooltip="true" width="140" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="协议" align="center" prop="protocolName" v-if="columns[19].visible"
                           :show-overflow-tooltip="true" width="180" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="通讯地址" align="center" prop="communicateAddress" v-if="columns[20].visible"
                           :show-overflow-tooltip="true" width="180" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <!--        2024-12-19新增字段-->
          <el-table-column label="通讯类型" align="center" prop="communicationType" v-if="columns[25].visible"
                           :show-overflow-tooltip="true" width="100" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.communication_type" :value="scope.row.communicationType"/>
            </template>
          </el-table-column>
          <!--        2024-12-19新增字段-->
          <el-table-column label="通讯配置" align="center" prop="communicationConfig" v-if="columns[26].visible"
                           :show-overflow-tooltip="true" width="180" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="经度" align="center" prop="lng" v-if="columns[21].visible"
                           :show-overflow-tooltip="true"
                           width="140" sortable="custom" :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="纬度" align="center" prop="lat" v-if="columns[22].visible"
                           :show-overflow-tooltip="true"
                           width="140" sortable="custom" :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="备注" align="center" prop="remark" v-if="columns[23].visible"
                           :show-overflow-tooltip="true" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
            <template slot-scope="scope">
<!--              <el-tooltip effect="dark" content="详情" placement="top">-->
<!--                <el-button-->
<!--                  size="mini"-->
<!--                  type="text"-->
<!--                  icon="el-icon-view"-->
<!--                  @click="handleDetail(scope.row)"-->
<!--                  v-hasPermi="['basedata:usersxb:edit']"-->
<!--                >-->
<!--                </el-button>-->
<!--              </el-tooltip>-->
              <el-tooltip effect="dark" content="修改" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['basedata:terminalsdb:edit']"
                  v-if="scope.row.terminalMark === 1"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="换表" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-sort"
                  v-hasPermi="['basedata:terminalsdb:edit']"
                  @click="handleReplaceTerminal(scope.row)"
                  v-if="scope.row.terminalMark === 1"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="销表" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-coordinate"
                  v-show="scope.row.terminalMark === 1"
                  v-has-permi="['basedata:terminaldb:cancelTerminal']"
                  @click="handleDeleteTerminal(scope.row)"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="删除" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['basedata:terminalsdb:remove']"
                  v-if="scope.row.terminalMark === 1"
                >
                </el-button>
              </el-tooltip>
<!--              v-show="scope.row.valvecontrol === 1 && scope.row.valvecontrol != null"-->
              <el-tooltip effect="dark" content="开阀" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-unlock"
                  @click="handleOpenValve(scope.row)"
                  v-has-permi="['basedata:termianldb:terminalDbCommand']"
                >
                </el-button>
              </el-tooltip>
<!--              v-show="scope.row.valvecontrol === 1 && scope.row.valvecontrol != null"-->
              <el-tooltip effect="dark" content="关阀" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-lock"
                  @click="handleCloseValve(scope.row)"
                  v-has-permi="['basedata:termianldb:terminalDbCommand']"
                >
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <el-dialog title="大用户详情" :visible.sync="detailVisible" width="1200px" :close-on-click-modal="false" fullscreen
               append-to-body @close="handleDetailClose">
      <el-tabs v-model="tabActiveKey" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="实时数据" name="1">
          <RealTime ref="refTerminalRealTime" v-if="tabActiveKey==='1'"/>
        </el-tab-pane>
        <el-tab-pane label="用量统计" name="2">
          <Dosage ref="refTerminalDosage" v-if="tabActiveKey==='2'"/>
        </el-tab-pane>
        <el-tab-pane label="历史数据" name="3">
          <History ref="refTerminalHistory" v-if="tabActiveKey==='3'"/>
        </el-tab-pane>
        <el-tab-pane label="数据趋势" name="4">
          <DataTrend ref="refTerminalDataTrend" v-if="tabActiveKey==='4'"/>
        </el-tab-pane>
        <el-tab-pane label="报警记录" name="5">
          <Alarm ref="refTerminalAlarm" v-if="tabActiveKey==='5'"/>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 添加或修改大档案对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body class="container-box">
      <el-form ref="form" :model="form" :rules="rules" :label-width="labelWidth" :inline="true">
        <el-form-item label="设备编号" prop="terminalId">
          <el-input v-model="form.terminalId" placeholder="请输入设备编号"/>
        </el-form-item>
        <el-form-item label="设备名称" prop="terminalName">
          <el-input v-model="form.terminalName" placeholder="请输入设备名称"/>
        </el-form-item>
        <el-form-item label="协议" prop="protocolId">
          <el-select v-model="form.protocolId" placeholder="请选择协议" style="width: 202px;">
            <el-option v-for="protocolItem in protocolOption" :key="protocolItem.protocolId"
                       :label="protocolItem.protocolName" :value="protocolItem.protocolId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="厂家名称" prop="supplierId">
          <el-select v-model="form.supplierId" filterable placeholder="请输入厂家名称" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.terminal_supplier"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表型号" prop="typeId">
          <el-select v-model="form.typeId" filterable placeholder="请选择表型号" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.module_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户编号" prop="userId">
<!--          <el-select v-model="form.userId" filterable style="width: 202px;">-->
<!--            <el-option v-for="user in usersXbList" :key="user.userId" :value="user.userId"-->
<!--                       :label=" user.userId + '：' + user.userName ">-->
<!--            </el-option>-->
<!--          </el-select>-->
          <el-input v-model="form.userId" placeholder="请输入用户编号" @focus="handleOpenUserTable"/>
        </el-form-item>
        <el-form-item label="区域名称" prop="sheetsCode">
          <treeselect v-model="form.sheetsCode"
                      :options="sheetsTreeList"
                      :normalizer="normalizer"
                      @select="handleSheetsChange"
                      :show-count="true"
                      placeholder="请选择区域名称"
                      style="width:202px;">
            <template v-slot:option-label="{ node, shouldShowCount, count }">
                  <span>
                    <!-- 这里添加你的图标，可以是字体图标或图片 -->
                    <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="node.raw.deviceType === 0"></span>
                    <span class="iconfont icon-loudong icon-padding" v-if="node.raw.deviceType === 1"></span>
                    <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="node.raw.deviceType === 2"></span>
                    {{ node.label}}
                    <!-- 如果需要，可以显示选中的数量 -->
                    <span v-if="shouldShowCount">({{ count }})</span>
                  </span>
            </template>
          </treeselect>
        </el-form-item>
        <el-form-item label="表底数" prop="baseReading">
          <el-input v-model="form.baseReading" placeholder="请输入表底数"/>
        </el-form-item>
        <el-form-item label="通讯地址" prop="communicateAddress">
          <el-input v-model="form.communicateAddress" placeholder="请输入通讯地址"/>
        </el-form-item>
        <el-form-item label="安装日期" prop="installDate">
          <el-date-picker clearable
                          v-model="form.installDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择安装日期"
                          style="width: 202px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="安装地址" prop="installAddress">
          <el-input v-model="form.installAddress" placeholder="请输入安装地址"/>
        </el-form-item>
        <el-form-item label="IMEI" prop="imei">
          <el-input v-model="form.imei" placeholder="请输入IMEI"/>
        </el-form-item>
        <el-form-item label="SIM卡号" prop="simNum">
          <el-input v-model="form.simNum" placeholder="请输入SIM卡号"/>
        </el-form-item>
        <el-form-item label="钢印/塑封号" prop="plasticSealNo">
          <el-input v-model="form.plasticSealNo" placeholder="请输入钢印/塑封号"/>
        </el-form-item>
        <el-form-item label="出厂编号" prop="firstSupplierId">
          <el-input v-model="form.firstSupplierId" placeholder="请输入出厂编号"/>
        </el-form-item>
        <el-form-item label="是否带阀控" prop="valveControl">
          <el-select v-model="form.valveControl" placeholder="请选择是否带阀控" style="width: 202px;">
            <el-option v-for="dict in dict.type.yes_no" :key="dict.value" :label="dict.label"
                       :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <!--        2024-12-19新增字段-->
<!--        <el-form-item label="阀门状态" prop="valveStatus">-->
<!--          <el-select v-model="form.valveStatus" placeholder="请选择阀门状态" style="width: 202px;">-->
<!--            <el-option label="开" :value="0"></el-option>-->
<!--            <el-option label="关" :value="1"></el-option>-->
<!--            <el-option label="无状态" :value="2"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="阀门地址" prop="valveAddress">
          <el-input v-model="form.valveAddress" placeholder="请输入阀门地址"/>
        </el-form-item>
<!--        2024-12-19新增字段-->
        <el-form-item label="通讯类型" prop="communicationType">
          <el-select v-model="form.communicationType" clearable placeholder="请选择通讯类型" style="width: 202px;">
            <el-option v-for="dict in dict.type.communication_type" :key="dict.value" :label="dict.label"
                       :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!--        2024-12-19新增字段-->
        <el-form-item label="通讯配置" prop="communicationConfig">
          <el-input v-model="form.communicationConfig" placeholder="请输入通讯配置"/>
        </el-form-item>
        <el-form-item label="出厂日期" prop="manufactureDate">
          <el-date-picker clearable
                          v-model="form.manufactureDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择出厂日期"
                          style="width: 202px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="口径大小" prop="caliber">
          <el-select v-model="form.caliber" placeholder="请选择口径" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.ldbd_pipe_caliber"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采集频率(分钟)" prop="readingFrequency">
          <el-input v-model="form.readingFrequency" placeholder="请输入采集频率"/>
        </el-form-item>
        <el-row>
          <el-form-item label="经度" prop="lng">
            <el-input v-model="form.lng" placeholder="请点击图标获取"/>
          </el-form-item>
          <el-form-item label="纬度" prop="lat">
            <el-input v-model="form.lat" placeholder="请点击图标获取"/>
          </el-form-item>
          <el-form-item>
            <i class="el-icon-location-information" style="color: #1890ff" @click="handleMap"></i>
          </el-form-item>
        </el-row>
        <el-form-item label="所属客户" prop="tenantId">
          <el-select filterable v-model="form.tenantId" placeholder="请选择所属客户" style="width: 202px;">
            <el-option
              v-for="dept in deptOption"
              :key="dept.tenantId"
              :label="dept.deptName"
              :value="dept.tenantId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传频率(分钟)" prop="upFrequency">
          <el-input v-model="form.upFrequency" placeholder="请输入上传频率"/>
        </el-form-item>
        <el-form-item label="注册平台" prop="signPlatform">
          <el-select v-model="form.signPlatform" placeholder="请选择注册平台" style="width: 202px;">
            <el-option v-for="dict in dict.type.sign_platform" :key="dict.value" :label="dict.label"
                       :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
<!--    换表对话框-->
    <el-dialog :title="title" :visible.sync="openReplace" width="740px" append-to-body>
      <el-form ref="replaceTerminalForm" :model="replaceTerminalForm" :rules="replaceTerminalRules" label-width="130px" :inline="true">
        <el-form-item label="旧设备编号" prop="terminalId">
          <el-input v-model="replaceTerminalForm.terminalId" placeholder="请输入旧设备编号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="新设备编号" prop="terminalIdNew">
          <el-input v-model="replaceTerminalForm.terminalIdNew" placeholder="请输入新设备编号"/>
        </el-form-item>
        <el-form-item label="旧IMEI" prop="imei">
          <el-input v-model="replaceTerminalForm.imei" placeholder="请输入旧IMEI" :disabled="true"/>
        </el-form-item>
        <el-form-item label="新IMEI" prop="imeiNew">
          <el-input v-model="replaceTerminalForm.imeiNew" placeholder="请输入新IMEI"/>
        </el-form-item>
        <el-form-item label="旧表底数" prop="baseReading">
          <el-input v-model="replaceTerminalForm.baseReading" placeholder="请输入表底数" :disabled="true"/>
        </el-form-item>
        <el-form-item label="新表底数" prop="baseReadingNew">
          <el-input v-model="replaceTerminalForm.baseReadingNew" placeholder="请输入表底数"/>
        </el-form-item>
        <el-form-item label="厂家名称" prop="supplierId">
          <el-select v-model="replaceTerminalForm.supplierId" filterable placeholder="请输入厂家名称" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.terminal_supplier"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表型号" prop="typeId">
          <el-select v-model="replaceTerminalForm.typeId" filterable placeholder="请选择表型号" clearable style="width: 202px;">
            <el-option
              v-for="dict in dict.type.module_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-form-item label="所属客户" prop="tenantId">
            <el-select filterable v-model="replaceTerminalForm.tenantId" placeholder="请选择所属客户" style="width: 202px;">
              <el-option
                v-for="dept in deptOption"
                :key="dept.tenantId"
                :label="dept.deptName"
                :value="dept.tenantId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区域名称" prop="sheetsCode">
            <treeselect v-model="replaceTerminalForm.sheetsCode" :options="sheetsTreeList" :normalizer="normalizer"
                        :show-count="true"
                        placeholder="请选择区域名称"
                        @select="handleSheetsChange"
                        :disable-branch-nodes="true"
                        style="width:202px;">
              <template v-slot:option-label="{ node, shouldShowCount, count }">
                  <span>
                    <!-- 这里添加你的图标，可以是字体图标或图片 -->
                    <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="node.raw.deviceType === 0"></span>
                    <span class="iconfont icon-loudong icon-padding" v-if="node.raw.deviceType === 1"></span>
                    <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="node.raw.deviceType === 2"></span>
                    {{ node.label}}
                    <!-- 如果需要，可以显示选中的数量 -->
                    <span v-if="shouldShowCount">({{ count }})</span>
                  </span>
              </template>
            </treeselect>
          </el-form-item>
          <el-form-item>
            <el-tooltip class="item" effect="dark" content="如果区域为灰，需要现在区域下添加楼栋" placement="bottom">
              <span class="iconfont icon-wenhao" style="color: #1890ff; font-size: 18px;"></span>
            </el-tooltip>
          </el-form-item>
        </el-row>
        <el-form-item label="协议" prop="protocolId">
          <el-select v-model="replaceTerminalForm.protocolId" placeholder="请选择协议" style="width: 202px;">
            <el-option v-for="protocolItem in protocolOption" :key="protocolItem.protocolId"
                       :label="protocolItem.protocolName" :value="protocolItem.protocolId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否带阀控" prop="valveControl">
          <el-select v-model="replaceTerminalForm.valveControl" placeholder="请选择是否带阀控" style="width: 202px;">
            <el-option v-for="dict in dict.type.yes_no" :key="dict.value" :label="dict.label"
                       :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阀门地址" prop="valveAddress">
          <el-input v-model="replaceTerminalForm.valveAddress" placeholder="请输入阀门地址"/>
        </el-form-item>
        <el-form-item label="安装日期" prop="installDate">
          <el-date-picker clearable
                          v-model="replaceTerminalForm.installDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择安装日期"
                          style="width: 202px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="安装地址" prop="installAddress">
          <el-input v-model="replaceTerminalForm.installAddress" placeholder="请输入安装地址"/>
        </el-form-item>
        <el-form-item label="注册平台" prop="signPlatform">
          <el-select v-model="replaceTerminalForm.signPlatform" placeholder="请选择注册平台" style="width: 202px;">
            <el-option v-for="dict in dict.type.sign_platform" :key="dict.value" :label="dict.label"
                       :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="changeRemark">
          <el-input v-model="replaceTerminalForm.changeRemark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReplaceTerminalForm">确 定</el-button>
        <el-button @click="cancelReplaceTerminal">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 定位对话框 -->
    <el-dialog
      width="700px"
      :title="mapdialog.title"
      :visible.sync="mapdialog.open"
      append-to-body
      @close="closeMapDialog"
      :destroy-on-close="true">
      <el-row class="line">
        <el-card shadow="never">
          <div id="mapContent" ref="mapContent"></div>
        </el-card>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="success" @click="initMap">获取当前位置</el-button> -->
        <el-button type="primary" @click="submitMap">确定</el-button>
      </div>
    </el-dialog>
    <!--        用户信息对话框-->
    <el-dialog :title="userTitle" :visible.sync="openUserTabel" width="840px" append-to-body @close="handleUserClose">
      <el-row>
        <el-col :span="19">
          <el-form :model="queryParamsUser" ref="queryFormUser" :size="formItemSize" label-width="75px">
            <div id="searchFilter" style="display: flex; flex-wrap: wrap">
              <el-form-item label="用户名称" prop="userName">
                <el-input
                  v-model="queryParamsUser.userName"
                  placeholder="请输入用户名称"
                  clearable
                  @keyup.enter.native="handleQuery"
                  style="width: 130px"
                />
              </el-form-item>
              <el-form-item label="用户编号" prop="userId">
                <el-input
                  v-model="queryParamsUser.userId"
                  placeholder="请输入用户编号"
                  clearable
                  @keyup.enter.native="handleQuery"
                  style="width: 130px"
                />
              </el-form-item>
              <el-form-item label="所属客户" prop="tenantId" v-if="systemFlag !== 2">
                <el-select filterable clearable v-model="queryParamsUser.tenantId" placeholder="请选择所属客户" style="width: 130px">
                  <el-option
                    v-for="dept in deptOption"
                    :key="dept.tenantId"
                    :label="dept.deptName"
                    :value="dept.tenantId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-form>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="userTableloading" :data="usersXbList" size="mini" row-key="id" border height="390px" ref="userTable"
                @selection-change="handleUserSelectionChange" @select="selectUser" :default-sort="defaultSort" @sort-change="handleUserSorterChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="用户编号" align="center" prop="userId"
                         :show-overflow-tooltip="true" sortable="custom"
                         :sort-orders="['ascending', 'descending']"/>
        <el-table-column label="用户名称" align="center" prop="userName"
                         :show-overflow-tooltip="true" sortable="custom"
                         :sort-orders="['ascending', 'descending']"/>
        <el-table-column label="所属客户" align="center" prop="deptName"
                         :show-overflow-tooltip="true"/>
        <el-table-column label="用户状态" align="center" prop="userMark"
                         :show-overflow-tooltip="true" sortable="custom"
                         :sort-orders="['ascending', 'descending']">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.user_status" :value="scope.row.userMark"/>
          </template>
        </el-table-column>
        <el-table-column label="立户时间" align="center" prop="createTime"
                         :show-overflow-tooltip="true" sortable="custom"
                         :sort-orders="['ascending', 'descending']">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="usertotal>0"
        :total="usertotal"
        :page.sync="queryParamsUser.pageNum"
        :limit.sync="queryParamsUser.pageSize"
        @pagination="getUserList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleUserOk">确 定</el-button>
        <el-button @click="handleUserCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptList } from '@/api/system/dept.js'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import moment from 'moment'
import {
  listTerminalsDb,
  getTerminalsDb,
  delTerminalsDb,
  addTerminalsDb,
  updateTerminalsDb,
  replaceTerminalsDb,
  cancelterminal,
  remoteControl
} from "@/api/record/terminalsdb";
import {getToken} from "@/utils/auth";
import RegisterDialog from '../../record/metered/component/registerDialog.vue'
import Dosage from './components/Dosage.vue'
import Alarm from './components/Alarm.vue'
import DataTrend from './components/DataTrend.vue'
import History from './components/History.vue'
import {gcj2bdString} from "@/utils/coordinate";
import {selectProtocol} from "@/api/basedata/protocol";
import RealTime from "./components/RealTime.vue";
import { getAreaTree } from "@/api/tree/index"
import {listUsersxb} from "@/api/record/usersxb";
import {mapState} from "vuex";
import {Message} from "element-ui";

export default {
  name: "Terminal",
  components: {RealTime, Treeselect, RegisterDialog, Dosage, Alarm, DataTrend, History},
  dicts: ['communication_type','user_status','warnparamtype', 'terminal_supplier', 'used_status', 'warntargettype', 'belongDepartment', 'module_type', 'ldbd_pipe_caliber', 'yes_no', 'default_position','sign_platform'],
  data() {
    return {
      // 用户信息表格查询条件
      queryParamsUser: {
        pageNum: 1,
        pageSize: 20,
        userName: null,
        userId: null,
        tenantId: null,
        userMark: 1,
        // unbound: null,
      },
      // 选中的用户数据
      userSelectData: [],
      usertotal: 0,
      userTableloading: false,
      userTitle:'',
      openUserTabel: false,
      ids: [],
      defaultExpandedKeys: [],
      treeWidth: '',
      // 客户下拉框中的数据
      deptOption: [],
      // 区域树加载状态
      treeLoading: false,
      // 关键字区域树
      filterText: null,
      // 屏幕高度
      screenHeight: null,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 区域管理表格数据
      terminalsdbList: [],
      // 弹出层标题
      title: "",
      // 区域树配置
      defaultProps: {
        children: "children",
        label: "sheetsName",
      },
      // 是否显示弹出层
      open: false,
      openReplace: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        terminalName: null,
        terminalId: null,
        imei: null,
        systemFlag: null,
        loginUserId: null,
        sheetsCode: null,
        tenantId: null,
        signPlatform: null,
      },
      // 列信息
      columns: [
        {key: 1, label: `设备名称`, visible: true},
        {key: 2, label: `设备编号`, visible: true},
        {key: 3, label: `表状态`, visible: true},
        {key: 4, label: `表型号`, visible: false},
        {key: 5, label: `表底数`, visible: false},
        {key: 6, label: `厂家名称`, visible: true},
        {key: 7, label: `安装日期`, visible: true},
        {key: 8, label: `安装地址`, visible: false},
        {key: 9, label: `IMEI`, visible: true},
        {key: 10, label: `SIM卡号`, visible: false},
        {key: 11, label: `钢印号`, visible: false},
        {key: 12, label: `出厂编号`, visible: false},
        {key: 13, label: `是否带阀控`, visible: true},
        {key: 14, label: `阀门地址`, visible: false},
        {key: 15, label: `出厂日期`, visible: false},
        {key: 16, label: `口径`, visible: true},
        {key: 17, label: `采集频率(分钟)`, visible: true},
        {key: 18, label: `上传频率(分钟)`, visible: true},
        {key: 19, label: `位置识别编号`, visible: false},
        {key: 20, label: `协议`, visible: false},
        {key: 21, label: `通讯地址`, visible: false},
        {key: 22, label: `经度`, visible: true},
        {key: 23, label: `纬度`, visible: true},
        {key: 24, label: `备注`, visible: true},
        {key: 25, label: `阀门状态`, visible: true},
        {key: 26, label: `通讯类型`, visible: true},
        {key: 27, label: `通讯配置`, visible: true},
      ],
      // 默认排序
      defaultSort: {prop: 'createTime', order: 'descending'},
      // 表单参数
      form: {},
      replaceTerminalForm: {},
      // 表单校验
      replaceTerminalRules: {
        terminalIdNew: [
          {required: true, message: "新设备编号不能为空", trigger: "blur"}
        ],
        imeiNew: [
          {required: true, message: "新IMEI不能为空", trigger: "blur"}
        ],
        baseReadingNew: [
          {required: true, message: "新表底数不能为空", trigger: "blur"}
        ],
      },
      rules: {
        supplierId: [
          {required: true, message: "厂家名称不能为空", trigger: "change"}
        ],
        communicateAddress: [
          {required: true, message: "通讯地址不能为空", trigger: "blur"}
        ],
        terminalName: [
          {required: true, message: "设备名称不能为空", trigger: "blur"}
        ],
        terminalId: [
          {required: true, message: "设备编号不能为空", trigger: "blur"}
        ],
        typeId: [
          {required: true, message: "表型号不能为空", trigger: "blur"}
        ],
        terminalIdNew: [
          {required: true, message: "设备编号不能为空", trigger: "blur"}
        ],
        installDate: [
          {required: true, message: "安装日期不能为空", trigger: "blur"}
        ],
        caliber: [
          {required: true, message: "口径大小不能为空", trigger: "change"}
        ],
        sheetsCode: [
          {required: true, message: "区域编号不能为空", trigger: "blur"}
        ],
        tenantId: [
          {required: true, message: "所属客户不能为空", trigger: "change"}
        ],
        protocolId: [
          {required: true, message: "协议不能为空", trigger: "change"}
        ],
        signPlatform: [
          {required: true, message: "注册平台不能为空", trigger: "change"}
        ],
        imei: [
          {required: true, message: "IMEI号不能为空", trigger: "blur"}
        ]
        /*   protocolId: [
             {required: true, message: "协议不能为空", trigger: "blur"}
           ],
           imeiNew: [
             {required: true, message: "新IMEI号不能为空", trigger: "blur"}
           ],*/
      },
      maxShow: 4,
      formItemSize: 'mini',
      collapseAble: false,
      fold: false,
      labelWidth: '120px',
      uploadVisible: false,
      currentTerminalId: null,
      currentTerminalLocationNb: null,
      detailVisible: false,
      tabActiveKey: '1',
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/basedata/terminalsdb/importData"
      },
      // 用户选项
      usersXbList: [],
      selectedUser: '', // 选中的用户
      // 协议下拉框中的数据
      protocolOption: [],
      // 区域树选项
      sheetsTreeList: [],
      // 地图
      map: {},
      // 定位弹窗参数
      mapdialog: {
        title: '定位',
        open: false,
      },
      // 位置
      position: {
        currentLat: '',
        currentLng: '',
        getLat: '',
        getLng: '',
        newformlng: '',
        newformlat: '',
        oldformlng: '',
        oldformlat: '',
        defaultPosition: []
      },
      TMapURL: 'http://api.tianditu.gov.cn/api?v=4.0&tk=b0948f5ee2a41b57f4c01444e00042ba'
    };
  },
  created() {
    this.getDeptList();
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - (this.showSearch ? (this.fold ? 295 : 255) : 195)
    },
    loginUserId() {
      return this.$store.state.user.userId
    },
    systemFlag() {
      return this.$store.state.user.systemFlag
    },
    ...mapState({
      systemFlag: state => state.user.systemFlag
    })
  },
  methods: {
    // 开阀
    handleOpenValve(row) {
      this.$modal.confirm('是否确认开启该表阀门？').then(function () {
        let form = Object.assign({}, row)
        if(form.protocolId === '7'){
          form.commandType = '0'
          form.values = {
            isOpen: '0'
          }
          form.terminalCode = form.terminalId
          remoteControl(form).then(response => {
            if (response.code === 200) {
              Message.success(response.msg)
              // this.getList()
            } else {
              Message.error(response.msg)
            }
          })
        }
      })
    },
    // 关阀
    handleCloseValve(row) {
      this.$modal.confirm('是否确认关闭该表阀门？').then(function () {
        let form = Object.assign({}, row)
        if(form.protocolId === '7') {
          form.commandType = '0'
          form.values = {
            isOpen: '1'
          }
          form.terminalCode = form.terminalId
          remoteControl(form).then(response => {
            if (response.code === 200) {
              Message.success(response.msg)
              // this.getList()
            } else {
              Message.error(response.msg)
            }
          })
        }
      })
    },
    // 用大用户表格排序
    handleUserSorterChange({column, prop, order}){
      this.queryParamsUser.orderByColumn = prop
      this.queryParamsUser.isAsc = order
      this.getUserList()
    },
    // 打开用大用户表格弹窗
    handleOpenUserTable(){
      this.userTitle="用户信息"
      this.openUserTabel = true
      this.getUserList()
    },
    // 关闭用户信息弹窗
    handleUserClose() {
      this.resetForm('queryFormUser')
      this.openUserTabel = false
    },
    // 用户信息弹窗确认
    handleUserOk(){
      if(this.title === '添加大用户档案' || this.title === '修改大用户档案'){
        this.form.userId = this.userSelectData.userId
      }
      // else if(this.title === '换表'){
      //   this.replaceMeteredForm.userId = this.userSelectData.userId
      // }
      this.openUserTabel = false
    },
    handleUserCancel() {
      this.openUserTabel = false
      this.resetForm('queryFormUser')
    },
    // 提交换表表单
    submitReplaceTerminalForm(){
      this.$refs["replaceTerminalForm"].validate(valid => {
        if (valid) {
          console.log(this.replaceTerminalForm,'form')
          replaceTerminalsDb(this.replaceTerminalForm).then(response => {
            if(response.code == 200){
              this.$modal.msgSuccess("换表成功");
              this.openReplace = false;
              this.getList();
            }
          });
        }
      });
    },
    // 销表
    handleDeleteTerminal(row) {
      this.reset()
      // 1使用中 0停用
      // this.form = row
      console.log(row,"row")
      if (row.terminalMark === 1) {
        this.$modal.confirm('是否确认停用编号为"' + row.terminalId + '"的表？').then(() => {
          return cancelterminal({id: row.id })
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("销表成功!");

        }).catch(() => {
        });
      } else if (row.terminalMark === 0) {
        this.$modal.msgWarning("此表已停用！");
      }
    },
    // 换表取消按钮
    cancelReplaceTerminal() {
      this.openReplace = false;
      this.resetReplaceTerminal();
    },
    // 重置换表表单
    resetReplaceTerminal() {
      this.resetForm('replaceTerminalForm')
    },
    // 大用户档案导入模版下载
    importTemplate(){
      this.download('basedata/terminalsdb/getImportTemplate', {}, `大用户档案导入模版_${new Date().getTime()}.xlsx`)
    },
    // 获取所有客户
    getDeptList() {
      deptList().then(response => {
        this.deptOption = response.data
      })
    },
    // 点击区域树节点
    handleNodeClick(data) {
      this.handleQuery()
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.sheetsName.indexOf(value) !== -1;
    },
    /** 排序触发事件 */
    handleSorterChange({column, prop, order}) {
      this.queryParams.orderByColumn = prop
      this.queryParams.isAsc = order
      this.getList()
    },
    /** 检查设置排序字段 */
    checkSortColumn() {
      if (!this.queryParams.orderByColumn) {
        this.queryParams.orderByColumn = this.defaultSort.prop
        this.queryParams.isAsc = this.defaultSort.order
      }
    },
    // 定位对话框打开
    handleMap() {
      this.mapdialog.title = '定位'
      this.mapdialog.open = true
      this.$nextTick(() => {
        this.initMap();
      })
    },
    // 定位对话框关闭
    closeMapDialog() {
      this.mapdialog.open = false
      this.map = new T.Map('mapContent');
    },
    // 换表
    handleReplaceTerminal(row) {
      this.resetReplaceTerminal();
      this.title = "换表";
      this.openReplace = true;
      const id = row.id
      getTerminalsDb(id).then(response => {
        this.replaceTerminalForm = response.data;
        this.openReplace = true;
        this.title = "换表";
      });
    },
    // 初始化地图
    initMap() {
      let pickup;
      let this_ = this
      const init = new Promise((resolve, reject) => {
        if (window.T !== 'undefined') {
          resolve(window.T)
        }
      })
      init.then(T => {
        this_.map = new T.Map('mapContent');
        this_.map.enableDrag()
        let point = new T.LngLat(this.dict.type.default_position[1].value, this.dict.type.default_position[0].value)
        this_.map.centerAndZoom(point, 12);
        this_.map.addOverLay(new T.Marker(point));
        this_.position.currentLat = this.dict.type.default_position[0].value
        this_.position.currentLng = this.dict.type.default_position[1].value
        let config = {
          callback: this_.getLngLat
        };
        pickup = new T.CoordinatePickup(this_.map, config); //获取当前鼠标点击位置的地理坐标
        pickup.addEvent();
      })
    },
    getLngLat(lnglat) {
      const x = lnglat.lng;
      const y = lnglat.lat; //纵坐标纬度
      this.map.clearOverLays(); // 清空原来的标注点
      let point = new T.LngLat(x, y);
      let marker = new T.Marker(point);
      this.map.addOverLay(marker); // 添加标注点
      this.getGeocoderFun(x, y);
    },
    // 根据经纬度获取地址
    async getGeocoderFun(lng, lat) {
      let T = window.T;
      let geocoder = new T.Geocoder();
      geocoder.getLocation(new T.LngLat(lng, lat), (result) => {
        this.position.currentLng = lng
        this.position.currentLat = lat
      });
    },
    submitMap() {
      let mapType = 'GAODE'
      // this.gcj2bdString(this.position.currentLng,this.position.currentLat, mapType)
      let positionArr = gcj2bdString(this.position.currentLng, this.position.currentLat, mapType)
      this.form.lng = positionArr[0]
      this.form.lat = positionArr[1]
      this.mapdialog.open = false
    },
    // 获取协议下拉框中的数据
    getSelectProtocol() {
      let TerminalType = 1
      selectProtocol(TerminalType).then(response => {
        this.protocolOption = response.data
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "大用户导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 查询区域管理列表 */
    getList() {
      this.checkSortColumn()
      this.loading = true;
      let choiceCheck = this.$refs.tree.getCurrentNode();
      if (choiceCheck !== null) {
        this.queryParams.sheetsCode = choiceCheck.sheetsCode
      }else{
        this.queryParams.sheetsCode = null
      }
      this.queryParams.systemFlag = this.systemFlag
      this.queryParams.loginUserId = this.loginUserId
      listTerminalsDb(this.queryParams).then(response => {
        this.terminalsdbList = response.rows;
        this.total = response.total
        this.loading = false;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: '' + node.sheetsCode,
        label: node.sheetsName,
        children: node.children
      };
    },
    // 区域下拉框改变触发事件
    handleSheetsChange(node){
      this.form.sheetsId = node.id
    },
    /** 查询区域树 */
    getTreeList() {
      this.treeLoading = true;
      // let treeType = "0,2"
      // getAreaTree(treeType).then(response => {
      //   this.sheetsTreeList = response.data;
      //   this.defaultExpandedKeys = [this.sheetsTreeList[0].id];
      //   this.treeLoading = false;
      // });
      this.sheetsTreeList = JSON.parse(localStorage.getItem('terminalTreeData'))
      if(this.sheetsTreeList.length === 0) {
        this.treeLoading = false;
      }else {
        this.defaultExpandedKeys = [this.sheetsTreeList[0].id];
        this.treeLoading = false;
      }
    },
    /** 查询用户下拉框 */
    getUserList() {
      this.userTableloading = true
      listUsersxb(this.queryParamsUser).then(response => {
        this.usersXbList = response.rows;
        this.usertotal = response.total;
        this.userTableloading = false
      });
    },
    handleUserQuery() {
      this.queryParamsUser.pageNum = 1;
      this.queryParamsUser.userMark = 1
      this.getUserList();
    },
    // 重置用大用户表格查询
    resetUserQuery() {
      this.resetForm("queryFormUser");
      this.handleUserQuery();
    },
    // 用大用户表格选择
    handleUserSelectionChange(val){
      this.userSelectData = val[0]
    },
    selectUser(selection, row){
      this.$refs.userTable.clearSelection();
      if(selection.length === 0){
        return
      }else{
        this.$refs.userTable.toggleRowSelection(row, true)
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        terminalId: null,
        terminalName: null,
        protocolId: null,
        supplierId: null,
        typeId: null,
        userId: null,
        sheetsCode: null,
        baseReading: null,
        communicateAddress: null,
        installDate: null,
        installAddress: null,
        imei: null,
        simNum: null,
        plasticSealNo: null,
        firstSupplierId: null,
        valveControl: null,
        valveAddress: null,
        manufactureDate: null,
        caliber: null,
        readingFrequency: null,
        lng: null,
        lat: null,
        tenantId: null,
        upFrequency: null,
        remark: null,
        communicationType: null,
        valveStatus: null,
        communicationConfig: null,
      };
      // this.form = {
      //   id: null,
      //   userId: null,
      //   terminalName: null,
      //   userPhone: null,
      //   idType: null,
      //   userCode: null,
      //   userAddress: null,
      //   remark: null,
      //   userMark: null
      // };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.$refs.tree.setCurrentKey(null)
      this.handleQuery();
    },
    // 表格多选框禁用
    selectable(row, rowIndex) {
      if (row.terminalMark === 1) {
        return true;  //不禁用
      } else {
        return false;  //禁用
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row) {
        this.form.parentId = row.id
      }
      this.open = true;
      this.title = "添加大用户档案";
    },
    handleDetail(row) {
      this.currentTerminalId = row.terminalId
      this.currentTerminalLocationNb = row.locationNb
      this.detailVisible = true
      this.$nextTick(() => {
        this.doLoadTabPaneData(this.tabActiveKey)
      })
    },
    handleDetailClose() {
      this.currentTerminalId = null
      this.tabActiveKey = '1'
    },
    handleTabClick(tab) {
      this.doLoadTabPaneData(tab._props.name)
    },
    doLoadTabPaneData(tabName) {
      this.$nextTick(() => {
        if (tabName === '1') {
          this.$refs.refTerminalRealTime.updateTerminalId(this.currentTerminalId)
          this.$refs.refTerminalRealTime.loadData()
        } else if (tabName === '2') {
          this.$refs.refTerminalDosage.updateTerminalLocationNb(this.currentTerminalLocationNb)
          this.$refs.refTerminalDosage.getList()
        } else if (tabName === '3') {
          this.$refs.refTerminalHistory.updateTerminalId(this.currentTerminalId)
          this.$refs.refTerminalHistory.getList()
        } else if (tabName === '4') {
          this.$refs.refTerminalDataTrend.updateTerminalId(this.currentTerminalId)
          this.$refs.refTerminalDataTrend.getList()
        } else {
          this.$refs.refTerminalAlarm.updateTerminalId(this.currentTerminalId)
          this.$refs.refTerminalAlarm.getList()
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getTerminalsDb(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改大用户档案";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTerminalsDb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTerminalsDb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.id || this.ids;
      this.$modal.confirm('是否确认删除所选记录？').then(function () {
        return delTerminalsDb(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basedata/terminalsdb/export', {
        ...this.queryParams
      }, `大用户档案数据.xlsx`)
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.formItemSize}`)
      const len = group?.length ? group?.length : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    }
  },

  mounted() {
    this.treeWidth = this.$refs['tree']?.$el.offsetWidth - 15
    this.getSelectProtocol();
    this.getTreeList();
    this.getUserList();
    this.getList();
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl();
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
};
</script>

<style scoped lang="scss">
//::v-deep .el-tabs__item.is-active {
//  color: rgb(255, 255, 255);
//  background-color: #409eff !important;
//  padding: 0px 10px 0px 10px;
//}
//::v-deep .el-tabs__item {
//  padding: 0px 10px;
//}

#mapContent {
  width: 100%;
  margin: 0 auto;
  height: 500px;
}
// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node{
    width: fit-content;
    min-width: var(--treeWidth);
  }
  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;
    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }

  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px ;
    font-size: 20px;
    background-size: 100% 100%;
  }
}
</style>
